package com.sz.freemusic.adapter;

import com.sz.data.Artist;
import com.sz.freemusic.R;
import com.sz.freemusic.common.ApplicationData;
import com.sz.freemusic.net.RequestQueue;
import com.sz.freemusic.net.listeners.ImageDownloadListener;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ArtistsListAdapter extends ArrayAdapter<Artist> implements ImageDownloadListener {
	
	private Activity context;
	
	static class ViewHolder {
		public ImageView artistImage;
		public TextView artistName;
		public TextView artistDescr;
	}

	public ArtistsListAdapter(Activity context) {
		super(context, R.layout.artist_list_item);
		this.context = context;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater layoutInflater = context.getLayoutInflater();
			rowView = layoutInflater.inflate(R.layout.artist_list_item, null);
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.artistImage = (ImageView) rowView.findViewById(R.id.artistImage);
			viewHolder.artistName = (TextView) rowView.findViewById(R.id.artist_name);
			viewHolder.artistDescr = (TextView) rowView.findViewById(R.id.artist_desc);
			ApplicationData.getInstance().setThSize(viewHolder.artistImage.getDrawable().getMinimumWidth(), 
					viewHolder.artistImage.getDrawable().getMinimumHeight());
			
			rowView.setTag(viewHolder);
		}
		RequestQueue.getInstance().enqueImageDownload(getItem(position), this);
		ViewHolder viewHolder = (ViewHolder) rowView.getTag();
		viewHolder.artistDescr.setText("Not available");
		viewHolder.artistName.setText(getItem(position).getName());
		Bitmap bmp = ApplicationData.getInstance().getBitmapCache().getBmpFromCache(getItem(position).getImageUrl());
		if (bmp != null) {
			viewHolder.artistImage.setImageBitmap(bmp);
		}
		return rowView;
	}
	
	@Override
	public void imageDone(Artist artist) {

		context.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				
				notifyDataSetChanged();
				
			}
		});
		
		
	}

}
